package com.itheima.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.exception.BusinessException;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component
public class AdminLoginManager {

    @Reference
    private AdminService adminService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //调用manager查询账号密码是否存在
    public void adminLogin(String username, String password, HttpServletResponse response) throws IOException {
        //根据username查询用户
        Admin admin = adminService.findByUserName(username);
        if (admin == null) {
            throw new BusinessException("用户名不存在");
        }
        //对比密码
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5, admin.getPassword())) {
            throw new BusinessException("密码输入错误!");
        }
        //生成token
        admin.setToken(null);
        Map<String, Object> map = BeanUtil.beanToMap(admin);
        String token = JwtUtil.createToken(map);
        //redis续期
        String json = JSON.toJSONString(admin);
        redisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofDays(7));
        //返回token
        HashMap<String, String> result = new HashMap<>();
        result.put("token", token);
        response.sendRedirect("http://127.0.0.1:18086?token=" + token);
    }
}
